<?php

namespace app\admin\logic;

use app\common\exception\ApiException;
use app\common\model\DealerAssistanceApplication;
use app\common\service\OpenSpoutWriter;
use support\Cache;
use think\facade\Db;

/**
 * 经销商申请逻辑层
 */
class DealerAssistanceApplicationLogic extends BaseLogic
{
    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->model = new DealerAssistanceApplication();
    }

    /**
     * 获取经销商申请列表
     * @param array $where
     * @return array
     */
    public function getDealerAssistanceApplications(array $where = [], int $page = 1, int $limit = 20): array
    {
        if (isset($where['create_time'][0])) {
            $where['create_time'] = parseDateRange($where['create_time']);
        } else {
            unset($where['create_time']);
        }
        $query = $this->search($where)->with(['dealer', 'company'])->order('id', 'desc');
        $list = $this->getList($query);
        return $list;
    }

    public function read($id): mixed
    {
        $model = $this->search(['id' => $id])->with(['dealer', 'company'])->findOrEmpty();
        if ($model->isEmpty()) {
            throw new ApiException('数据不存在');
        }
        return $model;
    }

    public function export(array $where = [])
    {
        if (isset($where['create_time'][0])) {
            $where['create_time'] = parseDateRange($where['create_time']);
        } else {
            unset($where['create_time']);
        }
        $query = $this->search($where)->with(['dealer', 'company'])->order('id', 'desc');
        $list = $this->getAll($query);
        
        foreach ($list as $item) {
            $export[] = [
                '经销商' => $item['dealer']['name'] ?? '',
                '县域' => $item['company']['name'] ?? '',
                '审批状态' => $item['apply_status_txt'] ?? '',
                '用款周期' => $item['loan_cycle_txt'] ?? '',
                '申请金额' => $item['apply_amount'] ?? '',
                '申请时间' => $item['create_time'] ?? '',
                '审批时间' => $item['update_time'] ?? '',
            ];
        }
        
        $fileName = '经销商扶助申请_'.date('YmdHis').'.xlsx';
        $header = ['经销商', '县域', '审批状态', '用款周期', '申请金额', '申请时间', '审批时间'];
        $width = [];
        foreach ($header as $key => $item) {
            $width[$key] = 18;
        }
        $writer = new OpenSpoutWriter($fileName);
        $writer->setHeader($header);
        $writer->setWidth(array_values($width));
        $writer->setData($export);
        $filePath = $writer->returnFile();
        return response()->download($filePath, urlencode($fileName));
    }
}
